package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.ValidateCodeUtils;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.Userservice;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author: HuangQi
 * @date: Created in 18:22 2023/9/8
 * @description: 用户表现层
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private Userservice userservice;


    /**
     * 发送手机短信验证码
     *
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        //获取手机号
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            //生成4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("生成的验证码为：{}", code);
            //调用阿里云提供的短信服务API完成发送短信
            //SMSUtils.sendMessage("瑞吉外卖", "", code, phone);

            //需要将验证码保存到session中
            session.setAttribute(phone, code);
            R.success("手机验证码短信发送成功");
        }
        return R.error("手机验证码短信发送失败");
    }


    /**
     * 移动端用户登录
     *
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session) {
        log.info("用户登录：{}", map);
        //获取手机号和验证码
        String phone = map.get("phone").toString();
        String userCode = map.get("code").toString();

        //从session中获取验证码
        String codeInSession = (String) session.getAttribute(phone);

        //进行验证码的校验
        if (codeInSession != null && codeInSession.equals(userCode)) {
            //如果比对成功,判断是否在用户表中
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);

            User user = userservice.getOne(queryWrapper);
            if (user == null) {
                //如果不在用户表中,新用户,需要将用户信息保存到用户表中
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userservice.save(user);
            }
            session.setAttribute("user",user.getId());
            //如果在用户表中,老用户
            return R.success(user);

        }

        return R.error("登录失败");
    }

}
